//
//  TimeButton.m
//  pa
//
//  Created by HaiJiao Chen on 12-7-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "TimeButton.h"
#include <time.h>

@implementation TimeButton
@synthesize currentTime;

- (void)timeSecond
{
    currentTime = time(nil);
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:currentTime];
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorian components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:date];
    [gregorian release];
    
    int hour = components.hour;
    int min = components.minute;
    NSString* apm = hour < 12 ? @"AM":@"PM";
    if (hour > 12)
    {
        hour -= 11;
    }
    NSString* title = [NSString stringWithFormat:@"%02d:%02d %@", hour, min, apm];
    [self setTitle:title forState:UIControlStateNormal];
}

- (void)initlize
{
    timer = [[KXTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeSecond) forMode:NSRunLoopCommonModes] retain];
    [self timeSecond];
    self.backgroundColor = [UIColor greenColor];
    [self setBackgroundImage:[UIImage imageNamed:@"btn_time_bg.png"] forState:UIControlStateNormal];
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.titleLabel setFont:[UIFont systemFontOfSize:12]];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initlize];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self initlize];
    }
    return self;
}
- (void)dealloc
{
    [timer invalidate];
    [timer release];
    [super dealloc];
}
@end
